package com.amap.rideroute;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.InfoWindowAdapter;
import com.amap.api.maps.AMap.OnInfoWindowClickListener;
import com.amap.api.maps.AMap.OnMapClickListener;
import com.amap.api.maps.AMap.OnMarkerClickListener;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RidePath;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.RouteSearch.OnRouteSearchListener;
import com.amap.api.services.route.RouteSearch.RideRouteQuery;
import com.amap.api.services.route.WalkRouteResult;
import com.amap.rideroute.util.AMapUtil;
import com.amap.rideroute.util.SortPathUtil;
import com.amap.rideroute.util.ToastUtil;
import com.amap.rideroute.overlay.RideRouteOverlay;

import java.util.ArrayList;
import java.util.List;


public class RideRouteActivity extends Activity implements OnMapClickListener,
        OnMarkerClickListener, OnInfoWindowClickListener, InfoWindowAdapter, OnRouteSearchListener, AMap.OnMapLoadedListener {
    private AMap aMap;
    private MapView mapView;
    private Context mContext;
    private RouteSearch mRouteSearch;
    private RideRouteResult mRideRouteResult;
    private LatLonPoint mStartPoint = new LatLonPoint(36.682871, 117.123232);//起点，39.996678,116.479271
    private LatLonPoint mEndPoint = new LatLonPoint(36.689582, 117.129498);//终点，39.997796,116.468939
    private final int ROUTE_TYPE_RIDE = 4;

    private RelativeLayout mBottomLayout;
    private TextView mRotueTimeDes, mRouteDetailDes;
    private ProgressDialog progDialog = null;// 搜索时进度条
    private List<LatLonPoint[]> latLonPoints;

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.route_activity);
        //模拟的多个位置
        List<LatLonPoint> points = new ArrayList<>();
        points.add(new LatLonPoint(36.682871,117.123232));
        points.add(new LatLonPoint(36.689582,117.129498));
        points.add(new LatLonPoint(36.684248,117.139325));
        latLonPoints = SortPathUtil.sortStraightPath(new LatLonPoint(36.689272,117.115722), points);
        Log.e("排序", latLonPoints.size() + "");
        mContext = this.getApplicationContext();
        mapView = (MapView) findViewById(R.id.route_map);
        mapView.onCreate(bundle);// 此方法必须重写
        init();
    }

    /**
     * 初始化AMap对象
     */
    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        registerListener();
        mRouteSearch = new RouteSearch(this);
        mRouteSearch.setRouteSearchListener(this);
        mBottomLayout = (RelativeLayout) findViewById(R.id.bottom_layout);
        mRotueTimeDes = (TextView) findViewById(R.id.firstline);
        mRouteDetailDes = (TextView) findViewById(R.id.secondline);
    }

    /**
     * 注册监听
     */
    private void registerListener() {
        aMap.setOnMapLoadedListener(RideRouteActivity.this);
        aMap.setOnMapClickListener(RideRouteActivity.this);
        aMap.setOnMarkerClickListener(RideRouteActivity.this);
        aMap.setOnInfoWindowClickListener(RideRouteActivity.this);
        aMap.setInfoWindowAdapter(RideRouteActivity.this);

    }

    @Override
    public View getInfoContents(Marker arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public View getInfoWindow(Marker arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onInfoWindowClick(Marker arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onMarkerClick(Marker arg0) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void onMapClick(LatLng arg0) {
        // TODO Auto-generated method stub

    }


    /**
     * 开始搜索路径规划方案
     */
    public synchronized void  searchRouteResult(LatLonPoint[] points,int routeType, int mode) {
//        showProgressDialog();
        final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
                points[0], points[1]);
        if (routeType == ROUTE_TYPE_RIDE) {// 骑行路径规划
            RideRouteQuery query = new RideRouteQuery(fromAndTo, mode);
            mRouteSearch.calculateRideRouteAsyn(query);// 异步路径规划骑行模式查询
        }
    }

    @Override
    public void onBusRouteSearched(BusRouteResult result, int errorCode) {

    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult result, int errorCode) {

    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult result, int errorCode) {

    }


    /**
     * 显示进度框
     */
    private void showProgressDialog() {
        if (progDialog == null)
            progDialog = new ProgressDialog(this);
        progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progDialog.setIndeterminate(false);
        progDialog.setCancelable(true);
        progDialog.setMessage("正在搜索");
        progDialog.show();
    }

    /**
     * 隐藏进度框
     */
    private void dissmissProgressDialog() {
        if (progDialog != null) {
            progDialog.dismiss();
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    public void onRideRouteSearched(final RideRouteResult result,final int errorCode) {
//        dissmissProgressDialog();
//        aMap.clear();// 清理地图上的所有覆盖物
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (errorCode == AMapException.CODE_AMAP_SUCCESS) {
                    if (result != null && result.getPaths() != null) {
                        if (result.getPaths().size() > 0) {
                            mRideRouteResult = result;
                            final RidePath ridePath = mRideRouteResult.getPaths()
                                    .get(0);
                            RideRouteOverlay rideRouteOverlay = new RideRouteOverlay(
                                    RideRouteActivity.this, aMap, ridePath,
                                    mRideRouteResult.getStartPos(),
                                    mRideRouteResult.getTargetPos());
                            rideRouteOverlay.removeFromMap();
                            rideRouteOverlay.addToMap();
                    rideRouteOverlay.zoomToSpan();
//                    mBottomLayout.setVisibility(View.VISIBLE);
//                    int dis = (int) ridePath.getDistance();
//                    int dur = (int) ridePath.getDuration();
//                    String des = AMapUtil.getFriendlyTime(dur) + "(" + AMapUtil.getFriendlyLength(dis) + ")";
//                    mRotueTimeDes.setText(des);
//                    mRouteDetailDes.setVisibility(View.GONE);
//                    mBottomLayout.setOnClickListener(new OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            Intent intent = new Intent(mContext,
//                                    RideRouteDetailActivity.class);
//                            intent.putExtra("ride_path", ridePath);
//                            intent.putExtra("ride_result",
//                                    mRideRouteResult);
//                            startActivity(intent);
//                        }
//                    });
                        } else if (result != null && result.getPaths() == null) {
                            ToastUtil.show(mContext, R.string.no_result);
                        }
                    } else {
                        ToastUtil.show(mContext, R.string.no_result);
                    }
                } else {
                    ToastUtil.showerror(mContext, errorCode);
                }
            }
        });
    }

    @Override
    public void onMapLoaded() {
        for (int i = 0; i < latLonPoints.size(); i++) {
            final LatLonPoint[] latLonPoint = latLonPoints.get(i);
            if(i == 0){
                for (int i1 = 0; i1 < latLonPoint.length; i1++) {
                    TextView textView = new TextView(this);
                    textView.setWidth(100);
                    textView.setHeight(100);
                    textView.setTextSize(20);
                    textView.setText((i1 + 1) + "");
                    aMap.addMarker((new MarkerOptions())
                            .position(new LatLng(latLonPoint[i1].getLatitude(),latLonPoint[i1].getLongitude())).icon(BitmapDescriptorFactory.fromView(textView)).title("\u8D77\u70B9"));
                }
            }else {
                TextView textView = new TextView(this);
                textView.setWidth(100);
                textView.setHeight(100);
                textView.setTextSize(20);
                textView.setText((i + 2) + "");
                aMap.addMarker((new MarkerOptions())
                        .position(new LatLng(latLonPoint[1].getLatitude(),latLonPoint[1].getLongitude())).icon(BitmapDescriptorFactory.fromView(textView)).title("\u8D77\u70B9"));
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    searchRouteResult(latLonPoint,ROUTE_TYPE_RIDE, RouteSearch.RIDING_DEFAULT);
                }
            }).start();
        }
    }
}

